using Microsoft.AspNetCore.Mvc;
using MediatR;
using Microsoft.Extensions.Caching.Memory;
using WeatherMcpServer;

namespace WeatherMcpServer.Controllers;

[ApiController]
[Route("api/[controller]")]
public class WeatherController : ControllerBase
{
    private readonly IHttpClientFactory _httpClientFactory;
    private readonly IMemoryCache _cache;
    private readonly IMediator _mediator;
    private readonly WeatherTool _tool;

    public WeatherController(IHttpClientFactory httpClientFactory, IMemoryCache cache, IMediator mediator)
    {
        _httpClientFactory = httpClientFactory;
        _cache = cache;
        _mediator = mediator;
        _tool = new WeatherTool(_httpClientFactory, _cache, _mediator);
    }

    public record EvaluateRequest(double Latitude, double Longitude, int DayOffset = 0);
    public record EvaluateByAddressRequest(string Address, int DayOffset = 0);

    [HttpPost("evaluate")]
    [ProducesResponseType(typeof(WeatherTool.EvaluateResult), StatusCodes.Status200OK)]
    public async Task<ActionResult<WeatherTool.EvaluateResult>> Evaluate([FromBody] EvaluateRequest req, CancellationToken ct)
    {
        var result = await _tool.EvaluateForecastIdsAsync(req.Latitude, req.Longitude, req.DayOffset);
        if (result is null) return BadRequest("评估失败，外部接口异常或未解析到有效预报");
        return Ok(result);
    }

    [HttpGet("forecast")]
    public async Task<IActionResult> GetForecast([FromQuery] double latitude, [FromQuery] double longitude)
    {
        if (double.IsNaN(latitude) || double.IsNaN(longitude))
            return BadRequest("Invalid coordinates.");

        var text = await _tool.GetForecastAsync(latitude, longitude);
        return Ok(new { text });
    }

    [HttpGet("forecast-by-address")]
    public async Task<IActionResult> GetForecastByAddress([FromQuery] string address)
    {
        if (string.IsNullOrWhiteSpace(address)) return BadRequest("address 不能为空");
        var text = await _tool.GetForecastByAddressAsync(address);
        return Ok(new { text });
    }

    [HttpPost("evaluate-by-address")]
    [ProducesResponseType(typeof(WeatherTool.EvaluateResult), StatusCodes.Status200OK)]
    public async Task<ActionResult<WeatherTool.EvaluateResult>> EvaluateByAddress([FromBody] EvaluateByAddressRequest req)
    {
        if (string.IsNullOrWhiteSpace(req.Address)) return BadRequest("address 不能为空");
        var result = await _tool.EvaluateByAddressAsync(req.Address, req.DayOffset);
        if (result is null) return BadRequest("评估失败，外部接口异常或未解析到有效预报");
        return Ok(result);
    }
}
